package ilincar.systemcore.tool;

import android.content.Context;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;

import android.os.Environment;
import android.util.Log;
import android.widget.Toast;

/**
 * Created by ilincar on 2016/12/9.
 */

public class ILog {
	
	private static final String TAG = "guoqz";

    public static void d(String tag, String msg) {

        if (Utils.isDebug) {
            Log.i(tag, msg);
        }

        if (Utils.isWriteDebug) {
            wirteLogToFile(tag, msg);
        }

    }
    
    public static void i(String msg) {

        if (Utils.isDebug) {
            Log.i(TAG, msg);
        }

    }


    public static void showMsg(Context context, String msg) {
        if (Utils.isShowToast) {
            Toast.makeText(context, msg, Toast.LENGTH_LONG).show();
        }
    }


    private static void wirteLogToFile(String tag, String msg) {
        String message = Utils.FILE_NAME_FORMATTER.format(new Date()) + " : " + tag + " : " + msg;
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            File dir = new File(Utils.LOG_PATH);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            File file = new File(Utils.LOG_PATH, Utils.LOG_FILE_NAME);
            if (file.length() > Utils.LOG_FILE_SIZE) {
                file.delete();
                file = new File(Utils.LOG_PATH, Utils.LOG_FILE_NAME);
            }
            FileWriter fileWriter = null;
            BufferedWriter bufferedWriter = null;
            try {
                fileWriter = new FileWriter(file, true);
                bufferedWriter = new BufferedWriter(fileWriter);
                bufferedWriter.write(message);
                bufferedWriter.newLine();
            } catch (IOException e) {

            } finally {
                try {
                    bufferedWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    fileWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
